package itsm.isperp.framework.quartz.executor;

import itsm.isperp.framework.quartz.domain.JobDefinition;
import itsm.isperp.framework.quartz.domain.JobState;
import itsm.isperp.framework.quartz.service.IJobService;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

/**
 * 任务扫描器,定时检查系统中是否有特定的任务需要启动
 * <ul>
 * <li>
 * 1、对于系统定义的任务进行扫描；扫描频率由isperp.scanJobCronExpression配置进行定义，默认为10分钟；</li>
 * <li>
 * 2、如果状态为running则启动任务并加入到作业调度器中；并更新其状态为run；</li>
 * <li>
 * 3、如果状态为stopping则停止任务并从作业调度中移除；并更新其整体为stop</li>
 * </ul>
 * 
 * @author JETSONLEE
 * @since 1.0
 * 
 * @param <T>
 *            继承于JobDefinition的实体
 */
public class ScanJobExecutor<T extends JobDefinition> implements Job {
	protected final Log logger = LogFactory.getLog(getClass());
	public static final String JOB_ID = "background_scan_job_definition";

	public void execute(JobExecutionContext context)
			throws JobExecutionException {
		@SuppressWarnings("unchecked")
		ScanJobExecutorDetail<T> jobDetail = (ScanJobExecutorDetail<T>) context
				.getJobDetail();

		IJobService<T> jobService = jobDetail.getJobService();
		List<T> jobDefinitions = jobService.loadJobs(JobState.running);
		logger.info("ScanJobExecutor started job that to be run.");
		logger.info("=====>There are " + jobDefinitions.size() + " jobs to run");

		try {
			for (T jobDef : jobDefinitions) {
				jobService.addJobToScheduler(jobDef);
				jobService.updateJobStatus(jobDef.getId(), JobState.run);
			}
			jobDefinitions = jobService.loadJobs(JobState.stopping);
			logger.info("ScanJobExecutor started job that to be stop.");
			logger.info("=====>There are " + jobDefinitions.size()
					+ " jobs to stop");
			for (T jobDef : jobDefinitions) {
				jobService.removeJobFromScheduler(jobDef.getId());
				jobService.updateJobStatus(jobDef.getId(), JobState.stop);
			}
		} catch (Exception ex) {
			logger.warn(ex);
		}
	}
}
